package com.newsee.remote.ecommerce.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.newsee.remote.SystemConfig;
import com.newsee.remote.common.bean.JsonResult;
import com.newsee.remote.common.bean.JsonReturn;
import com.newsee.remote.common.database.entity.ShMaterialclass;
import com.newsee.remote.common.database.mapper.ShMaterialclassMapper;
import com.newsee.remote.common.utils.tools.DateUtils;
import com.newsee.remote.common.utils.tools.SapXmlBuildUntil;
import com.newsee.remote.common.utils.webservice.HttpWebserviceExecutor;
import com.newsee.remote.ecommerce.service.IShMaterialclassService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.util.Calendar;
import java.util.Date;
import java.util.List;

/**
 * <p>
 * 物料分类服务实现类
 * </p>
 *
 * @author liangzhichen
 * @since 2019-07-22
 */
@Service
@Slf4j
public class ShMaterialclassServiceImpl extends ServiceImpl<ShMaterialclassMapper, ShMaterialclass> implements IShMaterialclassService {

    @Autowired
    private SystemConfig systemConfig;

    @Value("${materialClassUrl}")
    private String materialClassUrl;

    /**
     * sap请求物资主数据的url
     */
    private final static String MATERIAL_METHOD = "MT_IF1039_MATERIAL_CLASS_REQ";

    /**
     * 仓库请求start string
     */
    private final static String XML_START = "<soapenv:Envelope xmlns:soapenv=\"http://schemas.xmlsoap.org/soap/envelope/\" xmlns:urn=\"urn:sunac:erp:material_class\">";


    @Override
    public ShMaterialclass getIdByCode(String code) {
        QueryWrapper<ShMaterialclass> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("Code", code);
        return getOne(queryWrapper);
    }

    @Override
    public JsonResult pushMaterialClass(String startTime, String endTime) {
        log.info("推送增量物资分类...");
        //查询某时间段内的的增量数据（默认前一天的增量数据）
        List<ShMaterialclass> classes = getNeedUpdateMaterialClass(startTime, endTime);
        if (CollectionUtils.isEmpty(classes)) {
            log.info("当前时间段或前一天没有增量物资分类数据...");
            return JsonReturn.succ("当前时间段或前一天没有增量物资分类数据");
        }

        //请求业务体
        String message = getMessage(classes);
        //组装xml请求sap
        String request = SapXmlBuildUntil.makeXml(XML_START, MATERIAL_METHOD, systemConfig.getSapReqTarSys(), message);
        String response = HttpWebserviceExecutor.doHttpMethodSap(materialClassUrl, request, systemConfig.getSapAccount(), systemConfig.getSapPassword());
        return JsonReturn.succ(response);

    }

    /**
     * getMessage
     *
     * @param classes 分类信息s
     * @return message
     */
    private String getMessage(List<ShMaterialclass> classes) {
        StringBuilder message = new StringBuilder();
        message.append("<MESSAGE>\n");
        for (ShMaterialclass materialClass : classes) {
            message.append("<REQ_ITEM>\n");

            message.append("<Code>");
            if (StringUtils.isNotBlank(materialClass.getCode())) {
                message.append(materialClass.getCode());
            }
            message.append("</Code>\n");

            message.append("<ClassName>");
            if (StringUtils.isNotBlank(materialClass.getClassName())) {
                message.append(materialClass.getClassName());
            }
            message.append("</ClassName>\n");

            message.append("<ANCESTORNAME>");
            if (null != materialClass.getAncestorName()) {
                message.append(materialClass.getAncestorName());
            }
            message.append("</ANCESTORNAME>\n");

            message.append("<BusinessLineType>");
            if (null != materialClass.getBusinessLineType()) {
                message.append(materialClass.getBusinessLineType());
            }
            message.append("</BusinessLineType>\n");

            message.append("</REQ_ITEM>\n");
        }
        message.append("</MESSAGE>\n");
        return message.toString();
    }

    /**
     * 查询某时间段内的的增量数据（默认前一天的增量数据）
     *
     * @param startTime 开始时间
     * @param endTime   结束时间
     * @return 时间段内修改的物料分类
     */
    private List<ShMaterialclass> getNeedUpdateMaterialClass(String startTime, String endTime) {
        //没传时间默认取前一天增量的数据
        if (StringUtils.isBlank(startTime) && StringUtils.isBlank(endTime)) {
            Date date = new Date();
            Calendar c = Calendar.getInstance();
            c.add(Calendar.DATE, -1);
            Date yesterday = c.getTime();
            startTime = DateUtils.format(yesterday, "yyyy-MM-dd HH:mm:ss.sss");
            c.setTime(date);
            endTime = DateUtils.format(date, "yyyy-MM-dd HH:mm:ss.sss");
        }

        QueryWrapper<ShMaterialclass> queryWrapper = new QueryWrapper<>();
        queryWrapper.between("CreateDate", startTime, endTime)
                .or()
                .between("UpdateDate", startTime, endTime);
        return list(queryWrapper);
    }

}
